package com.coder.rental.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.coder.rental.entity.Order;
import com.coder.rental.entity.AutoInfo;
import com.coder.rental.mapper.AutoInfoMapper;
import com.coder.rental.service.IOrderService;
import com.coder.rental.utils.Result;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器，用于处理订单相关的HTTP请求
 * </p>
 *
 * @author KB
 * @since 2025-04-15
 */
@RestController
@RequestMapping("/rental/order")
public class OrderController {
    @Resource
    private IOrderService orderService;

    @Resource
    private AutoInfoMapper autoInfoMapper;

    @Value("${auto.info.maintain-mileage}")
    private Integer maintainMileage;

    /**
     * 保存订单信息
     * @param order 订单实体
     * @return 操作结果
     */
    @PostMapping
    public Result save(@RequestBody Order order){
        order.setOrderStatus(0);
        return orderService.insert(order)?Result.success():Result.fail();
    }


    /**
     * 查询未归还车辆的订单
     * @param start 分页起始位置
     * @param size 每页大小
     * @param order 查询条件
     * @return 查询结果
     */
    @PostMapping("/unfinished/{start}/{size}")
    public Result searchUnfinished(@PathVariable int start, @PathVariable int size,
                                   @RequestBody Order order){
        Page<Order> page = new Page<>(start,size);
        return Result.success(orderService.searchUnfinished(page,order));
    }

    /**
     * 查询订单信息
     * @param start 分页起始位置
     * @param size 每页大小
     * @param order 查询条件
     * @return 查询结果
     */
    @PostMapping("/{start}/{size}")
    public Result search(@PathVariable int start,@PathVariable int size,@RequestBody Order order){
        Page<Order> page = new Page<>(start,size);
        return Result.success(orderService.search(page,order));
    }

    /**
     * 更新订单信息
     * @param order 订单实体
     * @return 操作结果
     */
    @PutMapping
    public Result update(@RequestBody Order order){
        return orderService.returnAuto(order,maintainMileage)?Result.success():Result.fail();
    }

    /**
     * 统计车辆违规次数
     * @param autoId 车辆ID
     * @return 违规次数
     */
    @GetMapping("/countViolation/{autoId}")
    public Result countViolation(@PathVariable Integer autoId){
        long count=orderService.countViolation(autoId);
        return Result.success(count);
    }

    /**
     * 退还押金
     * @param orderId 订单ID
     * @return 操作结果
     */
    @GetMapping("/doReturnDeposit/{orderId}")
    public Result doReturnDeposit(@PathVariable Integer orderId){
        Order order = orderService.getById(orderId);
        order.setDepositReturn(1);
        return orderService.updateById(order)?Result.success():Result.fail();
    }

    /**
     * 更新订单状态
     * @param orderId 订单ID
     * @param status 新状态码
     * @return 操作结果
     */
    @PutMapping("/updateStatus/{orderId}/{status}")
    public Result updateOrderStatus(@PathVariable Integer orderId, @PathVariable Integer status) {
        Order order = orderService.getById(orderId);
        if (order == null) {
            return Result.fail().setMessage("订单不存在");
        }
        order.setOrderStatus(status);
        return orderService.updateById(order) ? Result.success() : Result.fail();
    }

    /**
     * 查询指定状态的订单
     * @param start 分页起始位置
     * @param size 每页大小
     * @param status 订单状态
     * @return 查询结果
     */
    @GetMapping("/status/{status}/{start}/{size}")
    public Result getOrdersByStatus(@PathVariable Integer status, 
                                   @PathVariable int start, 
                                   @PathVariable int size) {
        Page<Order> page = new Page<>(start, size);
        Order queryOrder = new Order();
        queryOrder.setOrderStatus(status);
        return Result.success(orderService.search(page, queryOrder));
    }

    /**
     * 取消订单
     * @param orderId 订单ID
     * @return 操作结果
     */
    @PutMapping("/cancel/{orderId}")
    public Result cancelOrder(@PathVariable Integer orderId) {
        Order order = orderService.getById(orderId);
        if (order == null) {
            return Result.fail().setMessage("订单不存在");
        }
        
        // 检查订单是否可取消
        if (order.getOrderStatus() > 1) {
            return Result.fail().setMessage("订单状态不允许取消");
        }
        
        // 更新订单状态为已取消(4)
        order.setOrderStatus(4);
        
        // 如果车辆已设为已租状态，恢复为未租状态
        if (order.getAutoId() != null) {
            AutoInfo autoInfo = autoInfoMapper.selectById(order.getAutoId());
            if (autoInfo != null && autoInfo.getStatus() == 1) {
                autoInfo.setStatus(0);
                autoInfoMapper.updateById(autoInfo);
            }
        }
        
        return orderService.updateById(order) ? Result.success() : Result.fail();
    }

    /**
     * 支付订单
     * @param orderId 订单ID
     * @return 操作结果
     */
    @PutMapping("/pay/{orderId}")
    public Result payOrder(@PathVariable Integer orderId) {
        Order order = orderService.getById(orderId);
        if (order == null) {
            return Result.fail().setMessage("订单不存在");
        }
        
        // 检查订单是否可支付
        if (order.getOrderStatus() != 0) {
            return Result.fail().setMessage("订单状态不允许支付");
        }
        
        // 更新订单状态为已支付(1)
        order.setOrderStatus(1);
        order.setRentActual(order.getRentPayable());
        
        return orderService.updateById(order) ? Result.success() : Result.fail();
    }
}
